<script setup name="FundPool">
import { Delete } from '@element-plus/icons-vue'
import Message from 'vue-m-message'
import fundPoolService from '@/api/finance/fundPool.js'
import zlPromptService from '@/api/finance/zlPrompt.js'
import BaseForm from '@/components/BaseForm/BaseForm.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { formatDate } from '@/utils/dayjs.js'
import { useDict } from '@/utils/dict.js'
import 'element-plus/theme-chalk/el-empty.css'
import useMessageBox from '@/utils/useMessageBox.js'

const tableData = ref([])
const tableData1 = ref([])
const poolList = ref([])
const demandNoteList = ref([])
const customerName = ref([])
const selectionList = ref([])
const queryParam = ref({})
const ids = ref([])
const matchIds = ref([])
const btnLoad = ref(false)
const updateDialogVisible = ref(false)
const updateDialogVisible1 = ref(false)
const auditVisible = ref(false)
const matchVisible = ref(false)
const updateDialogTitle = ref('新增')
const customerlist = ref([])
const formDisabled = ref(false)
const { proxy } = getCurrentInstance()
const { sys_proceeds_time, sys_pay_status, fund_pool_status } = useDict(
  'sys_proceeds_time',
  'sys_pay_status',
  'fund_pool_status',
)
const auditForm = ref({
  remark: '',
  status: '',
  cwbankcollectionId: '',
})
const searchConfig = reactive([
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerlist,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
  },
  {
    label: '收款时间',
    field: 'skTime',
    type: 'daterange',
    valueFormat: 'YYYY-MM-DD',
    defaultShow: true,
  },
  {
    label: '状态',
    field: 'status',
    type: 'select',
    defaultShow: true,
    options: {
      data: fund_pool_status,
      label: 'label',
      value: 'value',
      key: 'value',
    },
  },
])

const tableColumns = reactive([
  { type: 'checkbox', width: 50 },
  { type: 'seq', align: 'center', width: 50 },

  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 220,
  },
  {
    field: 'money',
    title: '已收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'skTime',
    title: '收款时间',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
    slots: { default: 'skTime' },
  },
  {
    field: 'syMoney',
    title: '剩余金额',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'status',
    title: '状态',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
    slots: { default: 'status' },
  },
  {
    field: 'remark',
    title: '审核意见',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 200,
    fixed: 'right',
    slots: { default: 'operate' },
  },
])
const tableColumns1 = reactive([
  { type: 'checkbox', width: 50 },
  { type: 'seq', align: 'center', width: 50 },

  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'dsMoney',
    title: '待收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'shMoney',
    title: '代理费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'syMoney',
    title: '官费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
])
const zjctableColumn = reactive([
  { type: 'seq', label: '序号', align: 'center', width: 50 },
  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'money',
    title: '已收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'skTime',
    title: '收款时间',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'syMoney',
    title: '剩余金额',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'status',
    title: '状态',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
    slots: { default: 'status' },
  },
])
const ckdtableColumn = reactive([
  { type: 'seq', label: '序号', align: 'center', width: 50 },
  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'dsMoney',
    title: '待收费用',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'shMoney',
    title: '代理费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'syMoney',
    title: '官费',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
])

const updateFormList = ref([
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerlist,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
    rules: [{ required: true, message: '请选择客户名称', trigger: 'blur' }],
    span: 24,
  },
  {
    label: '已收金额',
    field: 'money',
    type: 'input',
    rules: [{ required: true, message: '请输入已收金额', trigger: 'change' }],
    span: 24,
  },
  //   {
  //     label: "剩余金额",
  //     field: "syMoney",
  //     type: "input",
  //     rules: [{ required: true, message: "请输入剩余金额", trigger: "change" }],
  //     span: 24,
  //   },
  {
    label: '收款时间',
    field: 'skTime',
    type: 'date',
    rules: [{ required: true, message: '请选择收款时间', trigger: 'change' }],
    span: 24,
  },
])
const updateFormList1 = ref([
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerlist,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
    rules: [{ required: true, message: '请选择客户名称', trigger: 'blur' }],
    span: 24,
  },
  {
    label: '已收金额',
    field: 'money',
    type: 'input',
    rules: [{ required: true, message: '请输入已收金额', trigger: 'change' }],
    span: 24,
  },
  {
    label: '剩余金额',
    field: 'syMoney',
    type: 'input',
    rules: [{ required: true, message: '请输入剩余金额', trigger: 'change' }],
    span: 24,
  },
  {
    label: '收款时间',
    field: 'skTime',
    type: 'date',
    rules: [{ required: true, message: '请选择收款时间', trigger: 'change' }],
    span: 24,
  },
  //   {
  //     label: "状  态",
  //     field: "status",
  //     type: "input",
  //     rules: [{ required: true, message: "请输入状态", trigger: "change" }],
  //     span: 24,
  //     slots: { default: "status" },
  //   },
  //   {
  //     label: "备  注",
  //     field: "remark",
  //     type: "input",
  //     rules: [{ required: true, message: "请输入备注", trigger: "change" }],
  //     span: 24,
  //   },
])
const updateFormModel = ref({})
const updateFormModel1 = ref({})

const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  customerId: '',
})
const pagerConfig1 = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
// const matchForm=ref({
//     total: 0,
//   currentPage: 1,
//   pageSize: 10,
//   customerId: '',
// })

onMounted(() => {
  getList()
})

function getList() {
  const formData = {
    ...queryParam.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
  }
  btnLoad.value = true
  fundPoolService.list(formData).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    btnLoad.value = false
  })
  fundPoolService.optionList().then((res) => {
    customerlist.value = res.data
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange({ checked, records, reserves }) {
  selectionList.value = records
  const res = records.map(item => item.cwbankcollectionId)
  if (reserves.length > 0) {
    if (checked) {
      ids.value.push(...res)
    }
    else {
      const customerIdSet = new Set(reserves.map(item => item.customerId))
      ids.value = ids.value.filter(item => customerIdSet.has(item))
    }
  }
  else {
    ids.value = res
  }
}

function handleSearch(e, type) {
  if (type === 'reset') {
    customerName.value = []
  }
  queryParam.value = {
    'locationArea': customerName.value.join('/'),
    'params[beginSkTime]': e.skTime ? `${e.skTime[0]} 00:00:00` : null,
    'params[endSkTime]': e.skTime ? `${e.skTime[1]} 00:00:00` : null,
    ...e,
  }
  delete queryParam.value.skTime
  console.log(e)
  getList()
}

function handleUpdateSubmit(e) {
  console.log(e)
  const params = {
    ...e,
    skTime: e.skTime ? `${formatDate(e.skTime, 'YYYY-MM-DD')} 00:00:00` : null,
  }
  if (params?.cwbankcollectionId) {
    fundPoolService
      .update(params)
      .then((response) => {
        console.log('修改成功')
        Message.success('修改成功')
        updateDialogVisible1.value = false
        getList()
      })
      .finally(() => {})
  }
  else {
    fundPoolService.add(params).then((res) => {
      const { code } = res
      if (code === 200) {
        Message.success('新增成功')
        handleReset()
        getList()
      }
    })
  }
}

function handleReset() {
  updateDialogVisible.value = false
  updateDialogVisible1.value = false

  //   updateDialogTitle.value = "新增";
}

// 新增
function handleAdd() {
  updateDialogTitle.value = '新增'
  updateDialogVisible.value = true
  updateFormModel.value = {}
}
// 匹配催款单
function handleMatch() {
  updateDialogTitle.value = '匹配催款单'
  const hasDifferentCustomerId = selectionList.value.some(
    (item, index, array) => {
      return item.customerId !== array[0].customerId
    },
  )
  if (hasDifferentCustomerId) {
    Message.warning('请选择同一客户的催款单')
    return false
  }
  useMessageBox({
    title: '',
    description: `匹配成功`,
    icon: 'checksurface',
  }).then(() => {
    matchVisible.value = true
    getMatchList()
  })
}

function getMatchList() {
  console.log('666')
  pagerConfig1.value.customerId = selectionList.value[0].customerId
  zlPromptService.list(pagerConfig1.value).then((response) => {
    tableData1.value = response.rows.filter(item => item.status === '0')
    pagerConfig1.value.total = response.rows.filter(item => item.status === '0').length
  })
  //   CustomerQueryList().then(response => {
  //     this.customerlist = response.data
  //   })
}

function handleDelete(cwbankcollectionId) {
  const patentIds = cwbankcollectionId || ids.value
  fundPoolService.delete(patentIds).then((res) => {
    const { code } = res
    if (code === 200) {
      Message.success('删除成功')
      getList()
    }
  })
}

// 查看
function handleFormAction(row, type) {
  formDisabled.value = type === 'view'
  updateDialogTitle.value = type === 'view' ? '查看' : '修改'
  const id = row.cwbankcollectionId
  fundPoolService
    .getDetail(id)
    .then((response) => {
      //   updateFormModel.value.zlpromptId = response.data.zlpromptId;
      //   updateFormModel.value.remark = response.data.remark;
      updateFormModel1.value = response.data
      updateDialogVisible1.value = true
    })
    .catch((err) => {})
}

// 编辑修改
function handleEdit(row, type) {
  updateDialogTitle.value = type === 'view' ? '查看' : '编辑'
  formDisabled.value = false
  updateFormModel1.value = {
    customerId: row.customerId,
    skTime: row.skTime,
    money: row.money,
    syMoney: row.syMoney,
    cwbankcollectionId: row.cwbankcollectionId,
  }
  updateDialogVisible1.value = true
}

// 审核
function handleAudit(id) {
  updateDialogTitle.value = '审核'
  auditForm.value.cwbankcollectionId = id
  fundPoolService.auditPromptFundPool(id).then((res) => {
    demandNoteList.value = res
  })
  fundPoolService.auditFundPool(id).then((res) => {
    poolList.value = res
  })
  auditVisible.value = true
}

function handleExport() {
  proxy.download(
    'system/fundPool/export',
    { ...queryParam.value, exportIds: ids.value.join(',') },
    `user_${new Date().getTime()}.xlsx`,
  )
}

function cancel() {
  auditForm.value = {
    remark: '',
    status: '',
    cwbankcollectionId: '',
  }
  matchVisible.value = false
  auditVisible.value = false
}

function handleCheckChange1(data) {
  console.log(data.records, ids.value, 'data')
  matchIds.value = data.records.map(item => item.zlpromptId)
  // ids.value = tableCheckChane(data,'zlpromptId')
}
// 提交催款单
function matchSubmitForm() {
  const id = ids.value.join(',')
  const matchId = matchIds.value.join(',')
  if (!matchId) {
    Message.error('请选择数据！')
    return
  }
  const params = {
    fundPoolIds: id,
    promptIds: matchId,
  }
  console.log(params)
  fundPoolService.matchFundPool(params).then((response) => {
    if (response.code == 200) {
      Message.success('匹配成功')
      matchVisible.value = false
      getList()
    }
    else {
      matchVisible.value = false
      useMessageBox({
        title: '',
        description: `匹配失败！${response.msg}`,
        icon: 'warring',
      }).then(() => {
        getList()
      })
    }
  })
}

// 提交审核
function editSubmitForm() {
  console.log(auditForm.value, 'auditForm')
  fundPoolService.auditFundPoolDetail(auditForm.value).then((res) => {
    Message.success('审核成功')
    cancel()
    auditVisible.value = false
    getList()
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <SearchBar :search-config="searchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never">
      <div class="toolbar flex mb-1">
        <div class="mb-2 space-x-3">
          <el-button
            v-hasPermi="['system:finance:fundPool:match']"
            type="primary"
            class="el-gradient-primary"
            :disabled="ids.length === 0"
            @click="handleMatch()"
          >
            匹配催款单
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:fundPool:add']"
            type="primary"
            class="el-gradient-primary"
            @click="handleAdd()"
          >
            新增
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:fundPool:remove']"
            type="danger"
            class="el-gradient-danger"
            :disabled="ids.length === 0"
            @click="handleDelete(null)"
          >
            删除
            <el-icon class="el-icon--right">
              <Delete />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:fundPool:export']"
            type="warning"
            class="el-gradient-warning"
            @click="handleExport()"
          >
            导出
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
        </div>
        <RightToolbar />
      </div>
      <vxe-grid
        :row-config="{
          keyField: 'cwbankcollectionId',
        }"
        :data="tableData"
        :columns="tableColumns"
        :pager-config="pagerConfig"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellClass"
        :loading="btnLoad"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
        max-height="600px"
      >
        <template #status="{ row }">
          <dict-tag :options="fund_pool_status" :value="row.status" />
        </template>
        <template #skTime="{ row }">
          <span>{{ row.skTime.replace(/\s+.*/, "") }}</span>
        </template>
        <template #operate="{ row }">
          <el-button
            v-hasPermi="['system:finance:fundPool:query']"
            text
            type="success"
            size="small"
            @click="handleFormAction(row, 'view')"
          >
            查看
          </el-button>

          <el-button
            v-if="row.status === '1'"
            v-hasPermi="['system:finance:fundPool:audit']"
            text
            type="primary"
            size="small"
            @click="handleAudit(row.cwbankcollectionId, row.fundPoolIds)"
          >
            审核
          </el-button>

          <el-button
            v-if="row.status === '0'"
            v-hasPermi="['system:finance:fundPool:edit']"
            text
            type="primary"
            size="small"
            @click="handleEdit(row, 'edit')"
          >
            编辑
          </el-button>

          <span
            v-if="row.status === '0'"
            v-hasPermi="['system:finance:fundPool:remove']"
          >
            <el-popconfirm
              title="确认删除吗？"
              width="200px"
              @confirm="handleDelete(row.cwbankcollectionId)"
            >
              <template #reference>
                <el-button text size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </vxe-grid>
    </el-card>
    <!-- 新增 -->
    <el-dialog
      v-model="updateDialogVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      width="500px"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="updateFormList"
        :model="updateFormModel"
        class="px-5"
        @submit="handleUpdateSubmit"
        @cancel="handleReset"
      />
    </el-dialog>

    <!-- 查看 编辑 -->
    <el-dialog
      v-model="updateDialogVisible1"
      :destroy-on-close="true"
      class="custom-dialog"
      width="500px"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="updateFormList1"
        :model="updateFormModel1"
        class="px-5"
        :options="{ disabled: formDisabled }"
        @submit="handleUpdateSubmit"
        @cancel="handleReset"
      >
        <template #status="{ row }">
          <dict-tag :options="fund_pool_status" :value="row.status" />
        </template>
      </BaseForm>
    </el-dialog>

    <!-- 匹配催款单 -->
    <el-dialog
      v-model="matchVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <!-- <el-form :model="tableData1">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="tableData1.customerName"
                placeholder="请输入客户名称"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form> -->
      <vxe-grid
        :row-config="{
          keyField: 'zlpromptId',
        }"
        :data="tableData1"
        :columns="tableColumns1"
        :pager-config="pagerConfig1"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellContractClass"
        :loading="btnLoad"
        max-height="400px"
        border
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange1"
        @checkbox-change="handleCheckChange1"
      />
      <template #footer>
        <div class="flex-center mb">
          <el-button type="primary" @click="matchSubmitForm">
            确 定
          </el-button>
          <el-button @click="cancel()">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="auditVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      draggable
      top="5%"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="rules"
        label-width="120px"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否通过" prop="status">
              <el-radio-group v-model="auditForm.status">
                <el-radio label="1">
                  通过
                </el-radio>
                <el-radio label="0">
                  不通过
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核意见" prop="remark">
              <el-input
                v-model="auditForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入审核意见"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 资金池 -->
      <div class="linear-header my-7">
        <span>资金池</span>
      </div>
      <vxe-grid
        :data="poolList"
        :columns="zjctableColumn"
        header-cell-class-name="headerCellContractClass"
        :row-config="{
          keyField: 'cwbankcollectionId',
        }"
        border
        max-height="200px"
      >
        <template #status="{ row }">
          <dict-tag :options="fund_pool_status" :value="row.status" />
        </template>
      </vxe-grid>
      <!-- 催款单 -->
      <div class="linear-header my-7">
        <span>催款单</span>
      </div>
      <vxe-grid
        :data="demandNoteList"
        :columns="ckdtableColumn"
        header-cell-class-name="headerCellContractClass"
        :row-config="{
          keyField: 'zlpromptId',
        }"
        border
        max-height="200px"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :disabled="auditForm.status === ''"
            @click="editSubmitForm"
          >
            确 定
          </el-button>
          <el-button @click="cancel()">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.dialog-header {
  width: 180px;
  height: 0;
  border-width: 0px 45px 45px 0px;
  border-style: none solid solid;
  border-color: transparent transparent var(--el-color-primary);
  color: #fff;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  padding: 0px 10px 20px 0;
}
.mb{
  padding-bottom: 20px;
}
</style>
